
import { jobGoto } from "./goto";

/**@param {Room} room */
function findSource(room){
    let targets;
    let tombstones;
    {//tombstone
        tombstones=room.find(FIND_TOMBSTONES,{
            /**@param {Tombstone} spawn */
            filter:(tombstone)=>{
                return tombstone.store[RESOURCE_ENERGY] > 0;
            }
        });
    }
    if(tombstones.length > 0 && Math.random()<0.2){
        return tombstones;
    }
    {//container
        targets=room.find(FIND_STRUCTURES,{
            /**@param {Structure} */
            filter:(structure)=>{
                return structure.structureType==STRUCTURE_CONTAINER
                    && structure.store[RESOURCE_ENERGY]!=0;
            }
        });
    }
    if(targets.length > 0){
        return targets;
    }
    {//source
        targets=room.find(FIND_SOURCES,{
            /**@param {Source} source */
            filter:(source)=>{
                return source.energy > 0;
            }
        });
        targets.push(...tombstones);
    }
    return targets;
}
/**
 * @param {Creep} creep 
 * @param {Source} source 
 */
export function getEnergyFrom(creep, source){
    let ret=ERR_INVALID_TARGET;
    ret=creep.harvest(source);
    if(ret!=ERR_INVALID_TARGET){
        return ret;
    }
    ret=creep.withdraw(source,RESOURCE_ENERGY);
    if(ret!=ERR_INVALID_TARGET){
        return ret;
    }
    ret=creep.pickup(RESOURCE_ENERGY);

    return ret;
}
export const jobHarvest={
    /**
     * @param {Creep} creep 
     * @param {MoveToOpts} opts 
     */
    run:function(creep, opts = {visualizePathStyle:{stroke:"#aaaa00"}}) {
        let sources=creep.room.sources;
        if(sources==undefined){
            creep.room.sources = sources = findSource(creep.room);
        }
        if(sources.length==0){
            return;
        }
        sources=jobGoto.sortTargetsByDistance(creep, sources);
        let ret=OK;
        for(let source of sources){
            ret=getEnergyFrom(creep,source);
            switch(ret){
                case OK:
                    return OK;
                case ERR_NOT_IN_RANGE:
                    return jobGoto.run(creep,sources,opts);
                default:
                    
                    continue;
            }
        }
        return ret;
    }
}